package com.woniuxy.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.platform.infra.model.Resources;
import com.woniuxy.platform.infra.model.Role;
import com.woniuxy.platform.infra.model.RoleResource;
import com.woniuxy.platform.infra.mapper.RoleResourceMapper;
import com.woniuxy.platform.service.ResourcesService;
import com.woniuxy.platform.service.RoleResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.platform.service.RoleService;
import exception.MallException;
import org.springframework.stereotype.Service;
import result.CommonResultCodeEnum;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2023-07-19
 */
@Service
public class RoleResourceServiceImpl extends ServiceImpl<RoleResourceMapper, RoleResource> implements RoleResourceService {


    @Resource
    private ResourcesService resourcesService;

    @Resource
    private RoleService roleService;


    @Override
    public void addRoleResource(Integer roleId, Integer resourcesId) {
        Resources resources = resourcesService.getById(resourcesId);
        Role role = roleService.getById(roleId);
        if (resources==null||role==null){
            throw new MallException("资源或者角色不存在", CommonResultCodeEnum.INVALID_PARAM);
        }
        QueryWrapper<RoleResource> wrapper = new QueryWrapper<RoleResource>().eq("role_id", roleId).eq("resources_id", resourcesId);
        RoleResource roleResource = getOne(wrapper);
        if (roleResource!=null){
            throw new MallException("对应角色已有该资源",CommonResultCodeEnum.INVALID_PARAM);
        }
        RoleResource newRole = new RoleResource();
        newRole.setRoleId(roleId);
        newRole.setResourcesId(resourcesId);
        save(newRole);
    }

    @Override
    public void delRoleResource(Integer roleResourceId) {
        Resources resources = resourcesService.getById(roleResourceId);
        if (resources==null){
            throw new MallException("资源不存在",CommonResultCodeEnum.INVALID_PARAM);
        }
        removeById(roleResourceId);
    }

    @Override
    public List<String> checkRoleResource(Integer roleId) {
        QueryWrapper<RoleResource> wrapper = new QueryWrapper<RoleResource>().eq("role_id", roleId);
        List<RoleResource> list = list(wrapper);
        ArrayList<Integer> resourceIds = new ArrayList<>();
        for (RoleResource roleResource : list) {
            resourceIds.add(roleResource.getResourcesId());
        }
        Collection<Resources> resources = resourcesService.listByIds(resourceIds);
        List<String> pathLists = new ArrayList<>();
        for (Resources resource : resources) {
            pathLists.add(resource.getResourcesPath());
        }
        return pathLists;
    }
}
